package user

import (
	"context"
	"fmt"
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/core"
	file1 "gitee.com/binny_w/gin_starter/model/file"
	"go.uber.org/zap"
	"net/http"
)

var MdlUser *partner.TableModel

func init() {
	core.WaitCore.Wait()
	MdlUser = partner.NewTableModel(core.UserTable, "", nil)

	// 当数据表为空中，插入默认超级管理员
	if cnt, err := MdlUser.Table.Count(context.Background(), fmt.Sprintf("select count(*) from `%s` where 1 = 1", MdlUser.Table.Name)); err != nil {
		core.Logger.Panic("err to count user", zap.Error(err))
	} else if cnt == 0 {
		if err = InitAdmin(context.Background(), "root", core.Config.GetString("jwt-key")); err != nil {
			core.Logger.Panic("err to init admin", zap.Error(err))
		} else {
			core.Logger.Info("success to init admin", zap.String("admin", "root"))
		}
	}

	// 用户个人
	_ = MdlUser.RegisterGinHandler(http.MethodGet, "/my/info", myInfo)
	_ = MdlUser.RegisterGinHandler(http.MethodPatch, "/my/info", updateMyInfo)
	_ = MdlUser.RegisterGinHandler(http.MethodPatch, "/my/password", myPassword)
	_ = MdlUser.RegisterGinHandler(http.MethodPost, "/my/avatar", file1.UploadImage)
	_ = MdlUser.RegisterGinHandler(http.MethodPost, "/my/signature", file1.UploadImage)

	// 列表排序
	MdlUser.OrderBys["id_desc"] = "id desc"
	MdlUser.OrderBys["id_asc"] = "id asc"
	MdlUser.OrderBys["name_desc"] = "name desc"
	MdlUser.OrderBys["name_asc"] = "name asc"
	MdlUser.OrderBys["login_desc"] = "last_login desc"
	MdlUser.OrderBys["login_asc"] = "last_login asc"

	// 模糊搜索
	MdlUser.SoColumns = append(MdlUser.SoColumns, "name")

	// 登录
	_ = MdlUser.RegisterGinHandler(http.MethodPost, "/user/login", login)

	// 数据纠正
	MdlUser.InfoFixer = infoFixer
	MdlUser.InsertFixer = insertFixer
	MdlUser.QueryFixer = queryFixer
	MdlUser.UpdateFixer = updateFixer
	MdlUser.ListFixer = listFixer

	// 使用别人身份登录
	_ = MdlUser.RegisterGinHandler(http.MethodGet, "/user/act/:id", act)

	// 中间件，主要是为了对齐角色
	_ = MdlUser.UseGinMiddlewares(http.MethodPost, "/user", afterInsert)
	_ = MdlUser.UseGinMiddlewares(http.MethodDelete, "/user/:id", afterDelete)
	_ = MdlUser.UseGinMiddlewares(http.MethodPatch, "/user/:id", afterUpdate)

	core.Engine.RouterWithModel(core.ApiGroup, MdlUser)
}
